<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { loopShowTooltip } from '@/utils/echartAutoTooltip'

export default {
  mixins: [resize],
  props: {
    options: {
      type: Object,
      default: ()=>{}
    },
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    clickable: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    options: {
      handler(val){
        this.$nextTick(() => {
          this.initChart(val)
        })
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      chart: null,
    }
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.initChart()
    // })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(config) {
      this.chart = echarts.init(this.$el, 'macarons')
      config.legend.formatter = function(name){
        let d = config.series[0].data.filter((item)=>item.name===name);
        return name+" " + d[0].value;
      }
      this.chart && this.chart.setOption(config)
      if(this.clickable){
        this.chart.off("legendselectchanged");
        this.chart.on("legendselectchanged", (obj)=>{
          this.chart.setOption({
            legend:{selected:{[obj.name]: true}}
          })
          let val = config.series[0].data.filter((item)=>item.name===obj.name);
          this.$emit("legend-click",val[0]);
        })
      }
      
    }
  }
}
</script>
